package network.synchronizing;
import game.Game;

import java.util.Arrays;

import network.NetworkConstants;
import network.byteConversions.ByteConverter;
import physics.Body;
import physics.World;
import tools.Help;
import tools.Point;
public class SyncBody {
	public static byte[] getSyncData(Body b, Game g) {
		// if (b.unAcceleratedTime > 0.3f) return null;
		if (g.time - b.syncTime < NetworkConstants.SYNCINTERVALTIME) {
			return null;
		}
		byte[] data = new byte[28];
		System.arraycopy(ByteConverter.intToBytes(b.id), 0, data, 0, 4);
		System.arraycopy(ByteConverter.pointToBytes(b.pos), 0, data, 4, 8);
		System.arraycopy(ByteConverter.pointToBytes(b.vel), 0, data, 12, 8);
		System.arraycopy(ByteConverter.floatToBytes(b.apos), 0, data, 20, 4);
		System.arraycopy(ByteConverter.floatToBytes(b.avel), 0, data, 24, 4);
		b.syncTime = g.time;
		return data;
	}
	public static void readSyncData(World w, byte[] data, float time) {
		// float timeDiff = w.time - time;
		// if (timeDiff > NetworkConstants.ALLOWEDBSYNCTIMEDIFF) return;
		int id = ByteConverter.bytesToInt(Arrays.copyOfRange(data, 0, 4));
		if (!w.containsBodyId(id))
			return;
		Body b = w.getBodyById(id);
		if (b.syncTime > time) {
			return; // Another package that arrived earlier has been holding a
					// more recent state of the engine. Ignore this package.
		}
		b.syncTime = time;
		Point pos = ByteConverter.bytesToPoint(Arrays.copyOfRange(data, 4, 12));
		Point vel = ByteConverter.bytesToPoint(Arrays.copyOfRange(data, 12, 20));
		float apos = ByteConverter.bytesToFloat(Arrays.copyOfRange(data, 20, 24));
		float avel = ByteConverter.bytesToFloat(Arrays.copyOfRange(data, 24, 28));
		b.pos = pos;
		b.vel = vel;
		b.apos = apos;
		b.avel = avel;
	}
}
